import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_douban/config/Http_service.dart';
import 'package:flutter_douban/config/app_colors.dart';
import 'package:flutter_douban/main_page/home/detail/views/cook_detail_headerView.dart';
import 'package:flutter_douban/main_page/home/detail/views/nutrition_facts_view.dart';
import 'package:flutter_douban/main_page/home/h5_detail_page/activity_detail_page.dart';
import 'package:flutter_douban/main_page/home/notes/commit_cell.dart';
import 'package:flutter_douban/main_page/home/notes/note_detail_page.dart';
import 'package:flutter_douban/main_page/home/notes/note_list_page.dart';
import 'package:flutter_douban/main_page/home/video/window_video_page.dart';
import 'package:flutter_douban/model/content_model.dart';
import 'package:flutter_douban/model/note_content_model.dart';
import 'package:flutter_douban/model/note_model.dart';
import 'package:flutter_douban/model/recipe_big_model.dart';
import 'package:flutter_douban/tool_views/cached_network_Image.dart';
import 'package:flutter_douban/tool_views/photo_ViewScreen.dart';
import 'package:flutter_douban/tool_views/router.dart';
import 'package:flutter_douban/tool_views/stance_page.dart';
import 'package:sticky_headers/sticky_headers/widget.dart';

import '../../../../main.dart';
import 'cook_detail_navFooter.dart';
import 'cook_detail_navHeader.dart';

const APPBAR_SCROLL = 100; //设置滑动变化的偏移量

class CookDetailPage extends StatefulWidget {
  final int id;
  final String? imgUrl;
  const CookDetailPage({Key? key, required this.id,this.imgUrl}) : super(key: key);

  @override
  _CookDetailPageState createState() => _CookDetailPageState();
}

class _CookDetailPageState extends State<CookDetailPage> {
  RecipeBigModel? _model;
  List<NoteContentModel> _commotList = NoteContentModellList([]).list;
  List<NoteModel> _noteList = NoteModelList([]).list;

  /// 滚动控制器
  ScrollController? _controller;

  /// 关闭键盘
  FocusNode userFocusNode = FocusNode();

  /// 输入框
  late TextEditingController _textEditingController;
  double appBarAlpha = 0;
  double _offset = 0;

  /// 作品数量
  String _noteCount = '';

  /// 请求主体数据
  Future _getActiveData() async {
    try {
      /// 全部数据
      Map<String, dynamic> result =
          await HttpService.getCookDetailMianData(id: widget.id);
      Map<String, dynamic> result02 = result['recipe'];
      if (result02['nutrition_facts'] is List) {
      } else {
        result02['nutrition_facts'] = [];
      }

      /// 列表
      RecipeBigModel model = RecipeBigModel.fromJson(result02);
      setState(() {
        _model = model;
        _getDetailRecomomendData();
      });
    } catch (e) {
      print(e);
      setState(() {});
    } finally {
      setState(() {});
    }
  }

  /// 请求评论和笔记数据
  Future _getDetailRecomomendData() async {
    try {
      /// 全部数据
      Map<String, dynamic> result =
          await HttpService.getDetailCommentsData(id: widget.id);
      NoteContentModellList commotList =
          NoteContentModellList.fromJson(result['comments']);
      NoteModelList noteList = NoteModelList.fromJson(result['notes']);
      setState(() {
        _commotList = commotList.list;
        _noteList = noteList.list;
        _noteCount = result['recommendation_tag'];
      });
    } catch (e) {
      print(e);
      setState(() {});
    } finally {
      setState(() {});
    }
  }

  /// 监听列表偏移
  _onScroll(offset) {
    double alpha = offset / APPBAR_SCROLL;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      appBarAlpha = alpha;
      _offset = offset;
      userFocusNode.unfocus();
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getActiveData();
    _textEditingController = TextEditingController();
    _textEditingController.addListener(() {
      setState(() {});
    });
    _controller = ScrollController();
  }

  @override
  void dispose() {
    super.dispose();
    _textEditingController.dispose();
    _controller!.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_model?.title == null) {
      return StancePage();
      // return Container(
      //   height: MediaQuery.of(context).size.width*1.2,
      //   child: CachedImage(
      //     url: widget.imgUrl!,
      //     width: MediaQuery.of(context).size.width,
      //     height: MediaQuery.of(context).size.width*1.2,
      //   ),
      // );
    }

    /// 高度数组
    List<double> _headerList = [0, 40, 40];

    /// 头部widget
    List<Widget> _headerWidgetList = [
      _header('食材清单', '加入采购清单'),
      _header('食材清单', '加入采购清单'),
      _header('营养分析', '查看详情'),
    ];

    /// 内容widget
    List<Widget> _contentWidgetList = [
      CookDetailHeaderView(
        model: _model!,
      ),
      _cookNameWidget(),
      _nutritionWidget(),
    ];
    if (_model!.nutrition_facts?.length == 0) {
      _headerList.removeAt(2);
      _headerWidgetList.removeAt(2);
      _contentWidgetList.removeAt(2);
    }

    for (int i = 0; i < _model!.cookstep!.length; i++) {
      _headerList.add(35);
      _headerWidgetList.add(_cookHeader(i == _model!.cookstep!.length - 1
          ? '最后一步'
          : '步骤 ${i + 1}/${_model!.cookstep!.length}'));
      _contentWidgetList.add(_cookProcessWidget(i));
    }

    if (_model!.tips!.length > 0) {
      _headerList.add(40);
      _headerWidgetList.add(
        _header('小贴士', ''),
      );
      _contentWidgetList.add(_cookGuideWidget());
    }

    /// 评论数据
    if (_commotList.length > 0) {
      _headerList.add(40);
      _headerWidgetList.add(
        _header('热门评论', ''),
      );
      _contentWidgetList.add(_commitWidget());
    }

    /// 大家都在做
    if (_noteList.length > 0) {
      _headerList.add(40);
      _headerWidgetList.add(
        _header('大家做的这道菜', '   ' + _noteCount),
      );
      _contentWidgetList.add(_makeWidget());
    }

    /// 传学做
    _headerList.add(0);
    _headerWidgetList.add(
      _header('', ''),
    );
    _contentWidgetList.add(_studentWidget());

    return Scaffold(
        body: Container(
      color: Colors.white,
      child: Stack(
        children: <Widget>[
          MediaQuery.removePadding(
            removeTop: true,
            context: context,
            child: NotificationListener(
              onNotification: (scrollNotification) {
                if (scrollNotification is ScrollUpdateNotification &&
                    scrollNotification.depth == 0) {
                  //滚动且是列表滚动的时候
                  _onScroll(scrollNotification.metrics.pixels);
                }
                return true;
              },
              child: Container(
                color: Colors.white,
                padding: EdgeInsets.only(
                    top: appBarAlpha == 1
                        ? kToolbarHeight -
                            5 +
                            MediaQuery.of(context).padding.top
                        : 0,
                    bottom: MediaQuery.of(context).padding.bottom),
                child: ListView.builder(
                  primary: _controller == null,
                  controller: _controller,
                  itemCount: _headerList.length,
                  itemBuilder: (context, index) {
                    return StickyHeader(
                      // controller: _controller, // Optional
                      header: Container(
                        height: _headerList[index],
                        color: Colors.white,
                        padding: EdgeInsets.symmetric(horizontal: 16.0),
                        alignment: Alignment.centerLeft,
                        child: _headerWidgetList[index],
                      ),
                      content: _contentWidgetList[index],
                    );
                  },
                ),
              ),
            ),
          ),
          CoolDetailNavHeader(
            model: _model!,
            offset: _offset,
            appBarAlpha: appBarAlpha,
          ),
          Positioned(
              bottom: MediaQuery.of(context).padding.bottom,
              child: _bottowView())
        ],
      ),
    ));
  }

  /// 底部视图
  Widget _bottowView() {
    return Container(
      height: kToolbarHeight,
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.only(left: 20, right: 10),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
              color: Colors.black12,
              offset: Offset(0.0, -16.0), //阴影xy轴偏移量
              blurRadius: 10.0, //阴影模糊程度
              spreadRadius: 2.0 //阴影扩散程度
              )
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [_rightWidget(), _leftWidget()],
      ),
    );
  }

  Widget _rightWidget() {
    return Container(
      padding: EdgeInsets.only(left: 8, right: 8),
      alignment: Alignment.centerLeft,
      width: 150,
      height: 36,
      decoration: BoxDecoration(
        color: AppColors.line,
        borderRadius: BorderRadius.circular(20),
      ),
      child: TextField(
        focusNode: userFocusNode,
        style: TextStyle(color: Colors.black54, fontSize: 14),
        cursorColor: AppColors.yellow,
        controller: _textEditingController,
        decoration: InputDecoration.collapsed(
          hintText: "说点什么...",
          hintStyle: TextStyle(color: Colors.black54, fontSize: 14),
        ), //修改颜色),
        onSubmitted: (value) {
          if (_textEditingController.text.isNotEmpty) {
            _sendMsg(_textEditingController.text);
            _textEditingController.text = '';
          }
        },
      ),
    );
  }

  /// 发送消息
  void _sendMsg(String msg) {
    setState(() {
      _commotList.add(NoteContentModel(
          msg,
          '',
          'https://img1.chexun.com/chexunimg/erpimg/2020/0103/icon_default_d7578fdff611473b9f1b6af3155d06aa.jpg',
          '',
          1,
          '',
          '北京',
          11,
          11,
          [ContentModel(msg)],
          22,
          null,
          '',
          ''));
    });
    // _controller!.animateTo(0.0,
    //     duration: Duration(milliseconds: 300), curve: Curves.linear);
  }

  Widget _leftWidget() {
    return Row(
      children: [
        _itemWidget('icon_home_comment', '1'),
        _itemWidget('icon_home_collection', '收藏'),
        _itemWidget('bottom_recipe_dish', '传学做'),
      ],
    );
  }

  Widget _itemWidget(String icon, String name) {
    return Container(
      padding: EdgeInsets.only(left: 4, right: 4),
      child: Row(
        children: [
          Image.asset(
            'assets/images/common/${icon}.png',
            width: 22,
            height: 22,
          ),
          SizedBox(
            width: 5,
          ),
          Text(
            name,
            style: TextStyle(fontSize: 13, color: Colors.black),
          )
        ],
      ),
    );
  }

  /// 做饭食材
  Widget _cookNameWidget() {
    return Container(
      padding: EdgeInsets.only(left: 20, right: 20, bottom: 10, top: 10),
      child: ListView.builder(
          shrinkWrap: true,

          ///禁用滑动事件
          physics: NeverScrollableScrollPhysics(),
          itemCount: _model!.major!.length,
          itemBuilder: (BuildContext context, int index) {
            return Container(
              padding: EdgeInsets.only(top: 10, bottom: 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  InkWell(
                    child: Container(
                      width: MediaQuery.of(context).size.width - 200,
                      child: Text(
                        _model!.major![index].title!,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 17,
                            color: _model!.major?[index].tu?.isNotEmpty == true
                                ? Color.fromRGBO(94, 146, 140, 1)
                                : Colors.black),
                      ),
                    ),
                    onTap: () {
                      if (_model!.major?[index].tu?.isNotEmpty == true) {
                        Navigator.of(context)
                            .push(MaterialPageRoute(builder: (_) {
                          return ActivityDetail(
                            url: _model!.major?[index].tu,
                            titleStr: _model!.major![index].title!,
                          );
                        }));
                      }
                    },
                  ),
                  Container(
                    alignment: Alignment.topRight,
                    child: Text(
                      _model!.major![index].note!.trim(),
                      style: TextStyle(fontSize: 15, color: Colors.black),
                    ),
                    height: 20,
                    width: 160,
                    color: Colors.white,
                  )
                ],
              ),
            );
          }),
    );
  }

  /// 营养分析图
  Widget _nutritionWidget() {
    return Container(
      padding: EdgeInsets.only(left: 15, right: 15),
      width: MediaQuery.of(context).size.width,
      color: Colors.white,
      child: Column(
        children: [
          NutritionFactsView(dataArr: _model!.nutrition_facts!),
          SizedBox(
            height: 20,
          ),
          Row(
            children: [
              SizedBox(
                width: 5,
              ),
              Image.asset(
                'assets/images/common/recipe_tips_one_icon.png',
                width: 20,
                height: 20,
              ),
              SizedBox(
                width: 10,
              ),
              Text(
                // '这道菜低热量放心吃吧,点击了解更多健康知识!',
                _model!.nutrition_facts_hint_text!,
                style: TextStyle(
                    fontSize: 14,
                    color: Colors.black,
                    fontWeight: FontWeight.bold),
              ),
            ],
          ),
          SizedBox(
            height: 20,
          ),
          _header('烹饪步骤', '点击图片进入烹饪模式'),
          SizedBox(
            height: 10,
          ),
        ],
      ),
    );
  }

  /// 烹饪步骤
  Widget _cookProcessWidget(int index) {
    List<Widget> _cookList = [];
    if (index == _model!.cookstep!.length - 1) {
      _cookList = [
        Container(
            padding: EdgeInsets.only(bottom: 10),
            color: Colors.white,
            child: InkWell(
              child: ClipRRectCachedImage(
                // color: AppColors.page,
                url: _model!.cookstep![index].image!,
                width: MediaQuery.of(context).size.width,
                height: _model!.cookstep![index].image_height! *
                    MediaQuery.of(context).size.width /
                    _model!.cookstep![index].image_width!,
                radius: 10,
              ),
              onTap: () {
                Navigator.of(context).push(new FadeRouter(
                    child: PhotoViewGalleryScreen(
                      index: index,
                      dataArr: _model!.cookstep!,
                    ),
                    duration_ms: 500));
              },
            )),
        Text(
          _model!.cookstep![index].content!,
          strutStyle: StrutStyle(forceStrutHeight: true, height: 1, leading: 1),
          style: TextStyle(fontSize: 17, color: Colors.black),
        ),
        SizedBox(
          height: 15,
        ),
        Text(
          '发布于 ${_model!.create_time!}',
          strutStyle: StrutStyle(forceStrutHeight: true, height: 1, leading: 1),
          style: TextStyle(fontSize: 14, color: AppColors.qianTextColor),
        ),
      ];
    } else {
      _cookList = [
        Container(
            padding: EdgeInsets.only(bottom: 10),
            color: Colors.white,
            child: InkWell(
              child: ClipRRectCachedImage(
                url: _model!.cookstep![index].image!,
                width: MediaQuery.of(context).size.width,
                height: _model!.cookstep![index].image_height! *
                    MediaQuery.of(context).size.width /
                    _model!.cookstep![index].image_width!,
                radius: 10,
              ),
              onTap: () {
                Navigator.of(context).push(new FadeRouter(
                    child: PhotoViewGalleryScreen(
                      index: index,
                      dataArr: _model!.cookstep!,
                    ),
                    duration_ms: 500));
              },
            )),
        Text(
          _model!.cookstep![index].content!,
          strutStyle: StrutStyle(forceStrutHeight: true, height: 1, leading: 1),
          style: TextStyle(fontSize: 17, color: Colors.black),
        ),
      ];
    }

    return Container(
        padding: EdgeInsets.only(left: 15, right: 15, top: 5, bottom: 5),
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start, children: _cookList));
  }

  /// 头视图
  Widget _header(String title, String des) {
    return Row(
      mainAxisAlignment: title == '大家做的这道菜'
          ? MainAxisAlignment.start
          : MainAxisAlignment.spaceBetween,
      children: [
        Text(title,
            style: TextStyle(
                fontSize: 20,
                color: Colors.black,
                fontWeight: FontWeight.bold)),
        InkWell(
          child: Container(
            height: 30,
            child: Center(
              child: Text(des,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: 13,
                      color: Color.fromRGBO(94, 146, 140, 1),
                      fontWeight: FontWeight.w400)),
            ),
          ),
          onTap: () {
            if (title == '营养分析') {
              Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                return ActivityDetail(
                  url: _model!.nutrition_facts_url,
                  titleStr: '详细营养分析',
                );
              }));
            } else {
              Navigator.of(context).push(new FadeRouter(
                  child: PhotoViewGalleryScreen(
                    index: 0,
                    dataArr: _model!.cookstep!,
                  ),
                  duration_ms: 500));
            }
          },
        ),
      ],
    );
  }

  /// 烹饪步骤头视图
  Widget _cookHeader(String title) {
    return Text(
      title,
      style: TextStyle(
          color: Colors.black, fontSize: 15, fontWeight: FontWeight.bold),
    );
  }

  /// 小贴士
  Widget _cookGuideWidget() {
    return Container(
      padding: EdgeInsets.all(15),
      child: Text(
        _model!.tips!,
        strutStyle: StrutStyle(forceStrutHeight: true, height: 1, leading: 1),
        style: TextStyle(fontSize: 17, color: Colors.black),
      ),
    );
  }

  /// 评论
  Widget _commitWidget() {
    return Container(
      padding: EdgeInsets.only(left: 15, right: 15, top: 10),
      child: ListView.builder(
          shrinkWrap: true,

          ///禁用滑动事件
          physics: NeverScrollableScrollPhysics(),
          itemCount: _commotList.length + 1,
          itemBuilder: (BuildContext context, int index) {
            if (index == 0) {
              return Container(
                margin: EdgeInsets.only(bottom: 10),
                alignment: Alignment.centerLeft,
                height: 36,
                decoration: BoxDecoration(
                  color: AppColors.line,
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Row(
                  children: [
                    Image.asset(
                      'assets/images/common/sticker_face.png',
                      width: 40,
                      height: 40,
                    ),
                    Text(
                      '说点什么,让TA也认识爱做饭的你',
                      style: TextStyle(
                          fontSize: 12, color: AppColors.qianTextColor),
                    )
                  ],
                ),
              );
            } else {
              return CommitCell(
                model: _commotList[index - 1],
                commotList: _commotList,
                index: index,
              );
            }
          }),
    );
  }

  /// 大家在做
  Widget _makeWidget() {
    return Container(
      color: Colors.white,
      width: MediaQuery.of(context).size.width,
      height: 240,
      margin: EdgeInsets.only(top: 15, bottom: 10, left: 10, right: 10),
      child: ListView.builder(
          shrinkWrap: true,
          scrollDirection: Axis.horizontal,

          ///禁用滑动事件
          physics: AlwaysScrollableScrollPhysics(),
          itemCount: _noteList.length,
          itemBuilder: (BuildContext context, int index) {
            if (index == _noteList.length - 1) {
              return InkWell(
                child: _moWiget(index),
                onTap: (){
                  Navigator.of(context)
                      .push(MaterialPageRoute(builder: (_) {
                    return NoteListPage(id: widget.id,);
                  }));
                },
              );
            } else {
              return InkWell(
                child: _makeItem(index),
                onTap: () {
                  Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                    if (_noteList[index].video_url?.isNotEmpty == true) {
                      return WindowVideoPage(
                        playType: PlayType.network,
                        dataSource: _noteList[index].video_url!,
                        id: int.parse(_noteList[index].id!),
                      );
                    } else {
                      return NoteDetailPage(
                        id: int.parse(_noteList[index].id!),
                      );
                    }
                  }));
                },
              );
            }
          }),
    );
  }

  /// 高斯模糊cell
  Widget _moWiget(int index) {
    return ClipRRect(
        child: Stack(
      alignment: Alignment.center,
      children: <Widget>[
        ClipRRectCachedImage(
          url: _noteList[index].image_u!,
          width: 160,
          height: 240,
          radius: 8,
        ),
        Positioned.fill(
          child: BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 3, sigmaY: 3), //可以看源码
            child: Container(
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.6),
                borderRadius: BorderRadius.circular(8),
              ),
            ),
          ),
        ),
        Positioned(
            child: Text(
          '全部' + _noteCount,
          style: TextStyle(
              color: Colors.white, fontSize: 12, fontWeight: FontWeight.w400),
        ))
      ],
    ));
  }

  /// 大家在做cell
  Widget _makeItem(int index) {
    return Container(
        margin: EdgeInsets.only(left: 5, right: 5),
        color: Colors.white,
        child: Stack(
          children: [
            ClipRRect(
              child: ShaderMask(
                shaderCallback: (Rect bounds) {
                  return LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [Colors.black, Colors.transparent, Colors.black],
                  ).createShader(bounds);
                },
                blendMode: BlendMode.color,
                child: CachedImage(
                    url: _noteList[index].image_u!, width: 160, height: 240),
              ),
              borderRadius: BorderRadius.circular(8),
            ),
            Positioned(
              child: Container(
                height: 30,
                padding: EdgeInsets.only(left: 8),
                color: Colors.transparent,
                child: Row(
                  children: [
                    IconImage(
                      width: 22,
                      height: 22,
                      url: _noteList[index].author!.p!,
                      radius: 11,
                      borderColor: Colors.white,
                      borderWidth: 1.5,
                    ),
                    SizedBox(
                      width: 6,
                    ),
                    Text(
                      _noteList[index].author!.n!,
                      style: TextStyle(
                          fontSize: 11,
                          color: Colors.white,
                          fontWeight: FontWeight.w400),
                    )
                  ],
                ),
              ),
            )
          ],
        ));
  }

  /// 传学做
  Widget _studentWidget() {
    return Container(
      margin: EdgeInsets.only(left: 15, right: 15, top: 15, bottom: 60),
      height: 40,
      decoration: BoxDecoration(
        color: AppColors.yellow,
        borderRadius: BorderRadius.circular(20),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            'assets/images/common/comment_dish.png',
            width: 24,
            height: 24,
          ),
          SizedBox(
            width: 5,
          ),
          Text(
            '传学做',
            style: TextStyle(
                fontSize: 15, color: Colors.black, fontWeight: FontWeight.w500),
          )
        ],
      ),
    );
  }
}
